<template>
  <div class="container" v-infinite-scroll="load">
    <div class="search">
      <el-input
        @blur="searchBlur"
        @focus="searchFocus"
        @input="searchKeyWord"
        size="large"
        v-model="searchVal"
        placeholder="请输入商品关键字"
        :suffix-icon="Search"
      />
      <div class="search_items" v-show="searchShow && searchList.length">
        <div class="item" v-for="(item, index) in searchList" :key="index">
          {{ item.title }}
        </div>
      </div>
    </div>
    <div class="goods">
      <span>商品列表</span>
      <div class="list">
        <div
          class="item"
          @click="onDetail(item)"
          v-for="(item, index) in goodList"
          :key="index"
        >
          <el-image :src="baseUrl + item.cover" />
          <span>{{ item.title }}</span>
          <span>{{ item.desc }}</span>
          <span>￥{{ item.price }}</span>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { Search } from "@element-plus/icons-vue";
import { ref, onMounted } from "vue";
import { useRouter } from "vue-router";
import { goodIndex } from "@/http/api";
const router = useRouter();
const baseUrl = import.meta.env.VITE_API_URL;

const page = ref(1);
const more = ref(true);
const searchVal = ref("");
const searchShow = ref(false);
const goodList = ref([]);
const searchList = ref([]);

onMounted(() => {
  window.addEventListener("keydown", handkeyCode, true);
  getGoodList();
});

const handkeyCode = (e) => {
  if (e.keyCode == 13) {
    initList();
  }
};

const initList = () => {
  page.value = 1;
  goodList.value = [];
  getGoodList();
};

const onDetail = (e) => {
  console.log(e);
  router.push({
    name: "good",
    query: {
      id: e.id,
    },
  });
};

const searchBlur = () => {
  setTimeout(function () {
    initList();
    searchShow.value = false;
  }, 100);
};

const searchFocus = () => {
  searchShow.value = true;
  searchKeyWord();
};

const searchKeyWord = async () => {
  const { data } = await goodIndex({
    _keywords: searchVal.value,
    page: 1,
    limit: 5,
  });
  searchList.value = data.good.data;
};

const getGoodList = async () => {
  const { data } = await goodIndex({
    _keywords: searchVal.value,
    page: page.value,
    limit: 20,
  });
  const arr = data.good.data.map((el) => {
    el.cover = el.image.split(",")[0];
    return el;
  });
  arr.length ? goodList.value.push(...arr) : (more.value = false);
};

const load = () => {
  if (more.value) {
    page.value++;
    getGoodList();
  }
};
</script>

<style lang="scss" scoped>
@import "index.scss";
</style>
